package com.vimi8.chick.plugins.component;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;

import com.afollestad.materialdialogs.MaterialDialog;
import com.alibaba.weex.plugin.annotation.WeexComponent;
import com.shuyu.gsyvideoplayer.GSYVideoManager;
import com.shuyu.gsyvideoplayer.model.VideoOptionModel;
import com.shuyu.gsyvideoplayer.video.StandardGSYVideoPlayer;
import com.taobao.weex.WXSDKInstance;
import com.taobao.weex.dom.WXDomObject;
import com.taobao.weex.ui.component.WXComponent;
import com.taobao.weex.ui.component.WXComponentProp;
import com.taobao.weex.ui.component.WXVContainer;

import java.util.ArrayList;
import java.util.List;

import tv.danmaku.ijk.media.player.IjkMediaPlayer;

@WeexComponent(names = {"monitor-video"})
public class MonitorVideo extends WXComponent {
    private String mUrl;
    private boolean playerSupport = false;
    private StandardGSYVideoPlayer player;

    private static final int COMPLETED = 0;

    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
//            if (msg.what == COMPLETED) {
//
//            }
        }
    };

    public MonitorVideo(WXSDKInstance instance, WXDomObject dom, WXVContainer parent, int type) {
        super(instance, dom, parent, type);
        init(instance.getContext());
    }

    public MonitorVideo(WXSDKInstance instance, WXDomObject dom, WXVContainer parent, String
        instanceId, boolean isLazy) {
        super(instance, dom, parent, instanceId, isLazy);
        init(instance.getContext());
    }

    public MonitorVideo(WXSDKInstance instance, WXDomObject dom, WXVContainer parent, boolean isLazy) {
        super(instance, dom, parent, isLazy);
        init(instance.getContext());
    }

    public MonitorVideo(WXSDKInstance instance, WXDomObject dom, WXVContainer parent) {
        super(instance, dom, parent);
        init(instance.getContext());
    }

    private void init(Context context) {
        try {
            IjkMediaPlayer.loadLibrariesOnce(null);
            playerSupport = true;

            // 优化加载速度，降低延迟
            List<VideoOptionModel> list = new ArrayList<>();
            list.add(new VideoOptionModel(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "rtsp_transport", "tcp"));
            list.add(new VideoOptionModel(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "rtsp_flags", "prefer_tcp"));
            list.add(new VideoOptionModel(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "allowed_media_types", "video"));
            list.add(new VideoOptionModel(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "timeout", 20000));
            list.add(new VideoOptionModel(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "buffer_size", 1316));
            list.add(new VideoOptionModel(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "infbuf", 1));
            list.add(new VideoOptionModel(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "analyzemaxduration", 100));
            list.add(new VideoOptionModel(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "probesize", 10240));
            list.add(new VideoOptionModel(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "flush_packets", 1));
            // 关闭播放器缓冲，这个必须关闭，否则会出现播放一段时间后，一直卡主，控制台打印 FFP_MSG_BUFFERING_START
            list.add(new VideoOptionModel(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "packet-buffering", 0));
            GSYVideoManager.instance().setOptionModelList(list);
        } catch (Exception e) {
            e.printStackTrace();
            playerSupport = false;
        }
    }

    @Override
    protected View initComponentHostView(@NonNull Context context) {
        player = new StandardGSYVideoPlayer(context);
        player.setLayoutParams(new ViewGroup.LayoutParams(
            ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.MATCH_PARENT
        ));
        player.getTitleTextView().setVisibility(View.GONE);
        player.getBackButton().setVisibility(View.GONE);
        return player;
    }

    @WXComponentProp(name = "url")
    public void setStreamUrl(String url) {
        if (!TextUtils.isEmpty(url) && !url.equals(mUrl)) {
            mUrl = url;

            if (!playerSupport) {
                new MaterialDialog.Builder(getContext())
                    .title("播放失败")
                    .content("播放器不支持此设备")
                    .positiveText("确认")
                    .negativeText("取消")
                    .show();
            } else {
                player.setUp(url, true, "video");
                new PlayThread().start();
                //                player.startPlayLogic();
            }
        }
    }

    @Override
    public void destroy() {
        GSYVideoManager.releaseAllVideos();
        super.destroy();
    }

    @Override
    public void onActivityResume() {
        super.onActivityResume();
        if (player != null) {
            player.onVideoResume();
        }
    }

    @Override
    public void onActivityPause() {
        super.onActivityPause();
        if (player != null) {
            player.onVideoPause();
        }
    }

    @Override
    public boolean onActivityBack() {
        player.setVideoAllCallBack(null);
        return super.onActivityBack();
    }

    private class PlayThread extends Thread {
        @Override
        public void run() {
            player.startPlayLogic();

            Message msg = new Message();
            msg.what = COMPLETED;
            handler.sendMessage(msg);
        }
    }
}
